package com.fs.console.base.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.baseMapper.RoleMapper;
import com.fs.common.baseMapper.UserMapper;
import com.fs.common.baseMapper.UserRoleMapper;
import com.fs.common.pojo.User;
import com.fs.common.service.impl.SendSmsServiceImpl;
import com.fs.common.sms.vo.Passageway;
import com.fs.common.utils.ConcurrentHashMapCacheUtils;
import com.fs.console.base.annotation.PassToken;
import com.fs.console.base.enums.CodeEnum;
import com.fs.console.base.interceptor.AuthenticationInterceptor;
import com.fs.console.base.param.SysConstant;
import com.fs.console.base.service.LoginSerevice;
import com.fs.console.base.utils.ApplicationUtils;
import com.fs.console.base.utils.DateUtils;
import com.fs.console.base.utils.EncodeUtil;
import com.fs.console.base.vo.JsonResponse;
import com.fs.console.base.vo.LoginUser;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author ACE
 * @desc 登录controller
 * @creationTime 2019-08-12 11:25
 * @projectName yuezi-menu
 * @packageName com.fs.console.base.controller
 */
@Slf4j
@Controller
@RequestMapping("/console")
public class LoginController {
    @Autowired
    private LoginSerevice loginSerevice;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SendSmsServiceImpl sendSmsServiceImpl;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Setter @Getter @Value("${sms.comId}")
    private String comId;

    @Setter @Getter @Value("${sms.account}")
    private String account;

    @Setter @Getter @Value("${sms.pwd}")
    private String pwd;

    @Setter @Getter @Value("${sms.registeredUserCode}")
    private String registeredUserCode;

    @Setter @Getter @Value("${sms.forgetPasswordCode}")
    private String forgetPasswordCode;

    @Setter @Getter @Value("${sms.successRegisteredUserCode}")
    private String successRegisteredUserCode;

    @Setter @Getter @Value("${sms.currencyCode}")
    private String currencyCode;

    @Setter @Getter @Value("${sms.webLoginUrl}")
    private String webLoginUrl;

    @PassToken
    @ResponseBody
    @RequestMapping("/login")
    public JsonResponse login(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String account = map.get("account") == null ? "" : map.get("account").toString();
            String pwd = map.get("password") == null ? "" : EncodeUtil.getSignAndMD5(map.get("password").toString());
            String tokens = ApplicationUtils.getToken();
            if(StringUtils.isBlank(account) || StringUtils.isBlank(pwd)){
                if(StringUtils.isNotBlank(tokens)){
                    String s = AuthenticationInterceptor.map.get(tokens);
                    if(StringUtils.isNotBlank(s)){
                        User user = ApplicationUtils.getUser().getUser();
                        account = user.getAccount();
                        pwd = user.getPwd();
                    }else{
                        return JsonResponse.error(CodeEnum.EX108);
                    }
                }else{
                    return JsonResponse.error(CodeEnum.EX105);
                }
            }
            User user = new User(account,pwd);
            LoginUser loginUser = loginSerevice.login(user);
            Map loginMap = new HashMap();
            if(loginUser.getLoginStatus()){
                loginMap.put("loginUser", loginUser);
                String token = ApplicationUtils.getToken(loginUser);
                loginMap.put("token", token);
                //loginMap.put("userType",user.getUserType());
                AuthenticationInterceptor.loginUserMap.put(loginUser.getUser().getId(),loginUser);
                AuthenticationInterceptor.userCompanyMap.put(loginUser.getUser().getId(),loginUser.getCompanyList());
                AuthenticationInterceptor.map.put(token, DateUtils.curDate());
            }else{
                return JsonResponse.error(loginUser.getLoginResult());
            }
            JsonResponse jsonResponse = JsonResponse.success(loginMap);
            jsonResponse.setMsg(loginUser.getLoginResult());
            return jsonResponse;
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    /**
     * 推送公司全网短信平台
     * @return
     */
    /*@PassToken
    @ResponseBody
    @RequestMapping("/verificationCode")
    public JsonResponse verificationCode(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String mobile = map.get("mobile").toString();
            Object cache = ConcurrentHashMapCacheUtils.getCache(mobile);
            if(cache != null){
                List<String> strings = ApplicationUtils.decryptToken(cache.toString());
                Date date = DateUtils.parseDate(strings.get(1), SysConstant.DATA_DORMAT);
                Long times = new Date().getTime() - date.getTime();
                if(times < 1000 * 60){//1分钟
                    ConcurrentHashMapCacheUtils.deleteCache(mobile);
                    Integer second = (int)(times / 1000);
                    return JsonResponse.error(second.toString());
                }
            }
            int s = new Random().nextInt(9999)%(9999-1000+1) + 1000;
            String number = String.valueOf(s);
            String token = ApplicationUtils.getToken(number);
            ConcurrentHashMapCacheUtils.setCache(mobile,token);
            String msg = "您的验证码为"+number+"，请妥善保管，有效期5分钟。";
            sendSmsServiceImpl.sendVerificationCode(account,pwd,mobile,msg);
            log.info("msg:"+msg);
            return JsonResponse.success("发送成功！");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }*/

    /**
     * 推送阿里云短信平台
     * @return
     */
    @PassToken
    @ResponseBody
    @RequestMapping("/verificationCode")
    public JsonResponse verificationCode(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String mobile = map.get("mobile").toString();
            String type = map.get("type") == null ? "" : map.get("type").toString();
            Object cache = ConcurrentHashMapCacheUtils.getCache(mobile);
            if(cache != null){
                List<String> strings = ApplicationUtils.decryptToken(cache.toString());
                Date date = DateUtils.parseDate(strings.get(1), SysConstant.DATA_DORMAT);
                Long times = new Date().getTime() - date.getTime();
                if(times < 1000 * 60){//1分钟
                    ConcurrentHashMapCacheUtils.deleteCache(mobile);
                    Integer second = (int)(times / 1000);
                    return JsonResponse.error(second.toString());
                }
            }
            int s = new Random().nextInt(9999)%(9999-1000+1) + 1000;
            String number = String.valueOf(s);
            String token = ApplicationUtils.getToken(number);
            ConcurrentHashMapCacheUtils.setCache(mobile,token);
            List<String> mob = new ArrayList<>();
            mob.add(mobile);
            String code = currencyCode;
            String json = "{\"code\":\""+number+"\"}";
            if(type.equals("registeredUser")){
                code = registeredUserCode;
            }else if(type.equals("forgetPassword")){
                code = forgetPasswordCode;
            }
            Passageway passageway = Passageway.setAliyunPassageway(account, pwd, code, "主人翁健康", json, mob);
            String code1 = sendSmsServiceImpl.sendAliyunVerificationCode(passageway);
            log.info("验证码code:"+number);
            log.info("result:"+code1);
            return JsonResponse.success("发送成功！");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    @PassToken
    @ResponseBody
    @RequestMapping("/regPwd")
    public JsonResponse regPwd(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String mobile = map.get("mobile").toString();
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("mobile",mobile);
            User user = userMapper.selectOne(wrapper);
            if(user == null){
                return JsonResponse.error("帐号不存在，请输入正确的手机号码！");
            }
            Object cache = ConcurrentHashMapCacheUtils.getCache(mobile);
            if(cache == null){
                return JsonResponse.error("验证码已失效，请重新发送。");
            }
            String pwd = map.get("pwd").toString();
            String verificationCode = map.get("verificationCode").toString();
            List<String> strings = ApplicationUtils.decryptToken(cache.toString());
            Date date = DateUtils.parseDate(strings.get(1), SysConstant.DATA_DORMAT);
            Long times = new Date().getTime() - date.getTime();
            if(times > 1000 * 60 * 5){//5分钟
                ConcurrentHashMapCacheUtils.deleteCache(mobile);
                return JsonResponse.error("验证码已失效，请重新发送。");
            }
            if(!verificationCode.equals(strings.get(0))){
                return JsonResponse.error("验证码错误，请填写正确的验证码。");
            }
            user.setPwd(EncodeUtil.getSignAndMD5(pwd));
            userMapper.updateById(user);
            return JsonResponse.success("密码修改成功!");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    /*@PassToken
    @ResponseBody
    @RequestMapping("/register")
    public JsonResponse register(){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            String nickName = map.get("nickName").toString();
            String verificationCode = map.get("verificationCode").toString();
            String name = map.get("name").toString();
            String mobile = map.get("mobile").toString();
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("mobile",mobile);
            User user1 = userMapper.selectOne(wrapper);
            if(user1 != null){
                return JsonResponse.error("帐号已存在，请填写正确的手机号码。");
            }
            Object cache = ConcurrentHashMapCacheUtils.getCache(mobile);
            if(cache == null){
                return JsonResponse.error("验证码已失效，请重新发送。");
            }
            List<String> strings = ApplicationUtils.decryptToken(cache.toString());
            Date date = DateUtils.parseDate(strings.get(1), SysConstant.DATA_DORMAT);
            Long times = new Date().getTime() - date.getTime();
            if(times > 1000 * 60 * 5){//5分钟
                ConcurrentHashMapCacheUtils.deleteCache(mobile);
                return JsonResponse.error("验证码已失效，请重新发送。");
            }
            if(!verificationCode.equals(strings.get(0))){
                return JsonResponse.error("验证码错误，请填写正确的验证码。");
            }
            String password = BaseUtile.generatePassword(6);
            User user = new User();
            user.setId(UUID.randomUUID().toString().replaceAll("-",""));
            user.setPwd(EncodeUtil.getSignAndMD5(password));
            user.setAccount(nickName);
            user.setNickName(nickName + "用户");
            user.setComId(comId);
            user.setMobile(mobile);
            user.setAccount(mobile);//默认将手机号作为登录账号
            userMapper.insert(user);
            QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.eq("role_code", Role.YUE_ZI_ROLES);
            List<Role> roles = roleMapper.selectList(roleQueryWrapper);
            if(!CollectionUtils.isEmpty(roles)){
                UserRole userRole = new UserRole();
                userRole.setUserId(user.getId());
                userRole.setRoleId(roles.get(0).getId());
                userRoleMapper.insert(userRole);
            }
            sendInfoToRegister(mobile,password);
            return JsonResponse.success("申请成功！");
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResponse.error(CodeEnum.EX999);
        }
    }*/

    @PassToken
    @ResponseBody
    @RequestMapping("/register")
    public JsonResponse register(HttpServletRequest request){
        try {
            Map<String, Object> map = ApplicationUtils.getRequestDatas();
            User user = null;
            try {
                user = loginSerevice.register(map);
            }catch (Exception e){
                log.error(e.getMessage());
                return JsonResponse.error(e.getMessage());
            }
            if(null == user){
                return JsonResponse.error(CodeEnum.EX999);
            }else{
                sendInfoToRegister(user.getAccount(),user.getPwd());
            }
            return JsonResponse.success("申请成功！");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return JsonResponse.error(CodeEnum.EX999);
        }
    }

    private void sendInfoToRegister(String mobile,String password){
        String msg = "注册成功，您的帐号："+mobile+"，密码："+password+"，管理平台网址："+webLoginUrl+"，请尽快登录小程序或者平台修改密码。";
        List<String> mob = new ArrayList<>();
        mob.add(mobile);
        String json = "{\"account\":\""+mobile+"\",\"password\":\""+password+"\"}";
        Passageway passageway = Passageway.setAliyunPassageway(account, pwd, successRegisteredUserCode, "主人翁健康", json, mob);
        String code1 = sendSmsServiceImpl.sendAliyunVerificationCode(passageway);
        log.info("发送状态:"+code1+" 手机号："+mobile+"，发送信息："+msg);
    }
}
